<template>
  <!-- 角色表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1000px"
    draggable
    @close="closeDialog"
  >
    <div class="app-container" style="height: 500px">
      <!-- 列表 -->
      <el-card shadow="never" class="table-container">
        <template #header>
          <el-button type="success" plain @click="openDialog()">
            <i-ep-plus />
            新增
          </el-button>
        </template>

        <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="categoryData"
          highlight-current-row
          border
          row-key="id"
          :indent="30"
          default-expand-all
          :tree-props="{
            children: 'nodes',
            hasChildren: 'hasChildren',
          }"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="检测类目编号"
            prop="checkCategoryCode"
            minWidth="150"
            show-overflow-tooltip
          />
          <el-table-column
            label="检测类目名称"
            prop="checkCategoryName"
            show-overflow-tooltip
            minWidth="150"
            align="center"
          />
          <el-table-column
            fixed="right"
            label="操作"
            width="300"
            align="center"
          >
            <template #default="scope">
              <el-button
                type="success"
                size="small"
                @click="addParentDialog(scope.row)"
              >
                <i-ep-plus />
                添加子类目
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="openDialog(scope.row)"
              >
                <i-ep-edit />
                编辑
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="handleTableDelete(scope.row.id)"
              >
                <i-ep-delete />
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 新增 -->
      <checkcategory-edit
        :visible="addDialog.visible"
        :title="addDialog.title"
        :data="addDialog.data"
        :parentId="addDialog.parentId"
        @reset-table="(id:string) => getCategoryData(formData.id)"
        @change-visible="changeVisible"
      />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关 闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
/** 打开检测方案表单弹窗 */
function openDialog(roleObj?: any) {
  if (roleObj) {
    addDialog.title = "修改检测方案";
    addDialog.data = {
      id: roleObj.id,
      schemeId: roleObj.schemeId,
      schemeCode: roleObj.schemeCode,
      schemeName: roleObj.schemeName,
      parentCategoryId: roleObj.parentCategoryId,
      checkCategoryCode: roleObj.checkCategoryCode,
      checkCategoryName: roleObj.checkCategoryName,
      allId: roleObj.allId,
      allCode: roleObj.allCode,
      allName: roleObj.allName,
      version: roleObj.version,
      remarks: roleObj.remarks,
      lastUpdateTime: roleObj.lastUpdateTime,
      createdUserId: roleObj.createdUserId,
      createdUserName: roleObj.createdUserName,
      delete: roleObj.delete,
    };
  } else {
    addDialog.title = "新增检测方案";
    addDialog.data = {
      schemeId: formData.id,
      schemeCode: formData.schemeCode,
      schemeName: formData.schemeName,
      parentCategoryId: "0",
    };
  }
  addDialog.readvisible = false;
  addDialog.visible = true;
  console.log("addDialog", addDialog);
}
/** 打开检测方案表单弹窗 */
function addParentDialog(roleObj?: any) {
  if (roleObj) {
    addDialog.title = "添加子目录";
    addDialog.data = {
      schemeId: formData.id,
      schemeCode: formData.schemeCode,
      schemeName: formData.schemeName,
      parentCategoryId: roleObj.id,
    };
  }
  addDialog.readvisible = false;
  addDialog.visible = true;
}
defineOptions({
  name: "MDMCHECKSCHEMEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
let categoryData = ref([]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const rules = reactive({
  schemeCode: [{ required: true, message: "请输入方案代码", trigger: "blur" }],
  businessDomain: [
    { required: true, message: "请输入业务领域", trigger: "blur" },
  ],
  checkTypeId: [
    { required: true, message: "请输入检测类别id", trigger: "blur" },
  ],
  organizationId: [
    { required: true, message: "请输入公司ID;基本信息", trigger: "blur" },
  ],
  plantId: [{ required: true, message: "请输入工厂id", trigger: "blur" }],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  schemeId: "",
  schemeCode: "",
  schemeName: "",
  businessDomain: "",
  checkTypeId: "",
  organizationId: "",
  plantId: "",
  version: "",
  remarks: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        schemeCode,
        schemeName,
        businessDomain,
        checkTypeId,
        organizationId,
        plantId,
        version,
        remarks,
      } = newVal;
      Object.assign(formData, {
        id,
        schemeCode,
        schemeName,
        businessDomain,
        checkTypeId,
        organizationId,
        plantId,
        version,
        remarks,
      });
      console.log("formData123", formData);
      getCategoryData(formData.id);
    }
  }
);
// 删除
async function handleTableDelete(id: string) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/mdm/checkcategory/delete`,
      method: "post",
      data: { ids: [id] },
    })
      .then(() => {
        ElMessage.success("删除成功");
        getCategoryData(formData.id);
      })
      .catch(() => ElMessage.info("已取消删除"));
  });
}
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  // formRef.value.resetFields();
  // formRef.value.clearValidate();
  formData.id = "";
  formData.schemeId = "";
  formData.schemeCode = "";
  formData.schemeName = "";
  formData.businessDomain = "";
  formData.checkTypeId = "";
  formData.organizationId = "";
  formData.plantId = "";
  formData.version = "";
  formData.remarks = "";
}

const loading = ref(false);

/** 检测方案查询详细表 */
async function getCategoryData(id: string) {
  const data = await request({
    url: "/mdm/checkcategory/getList/" + id,
    method: "get",
  });
  categoryData.value = data.data;
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
</script>
